package br.ufc.pet.util.email;

import java.util.ArrayList;
import java.util.Properties;
 
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Sender {
	
	private String email;
	private String password;
	private Session session;
	private Properties configProperties;

	public Sender(String email, String password){
		this.email = email;
		this.password = password;
		
		configureProperties();
		
		createSession();
		
	}
	
	public void send(String subject, String address, String messageText){
        
        try{

        	Message message = new MimeMessage(session);
        	
        	message.setFrom(new InternetAddress(email));
        	
        	InternetAddress[] dest = InternetAddress.parse(address);
        	
        	message.setRecipients(Message.RecipientType.TO,dest);
        	
        	message.setSubject(subject);
        	
        	message.setText(messageText);
        	
        	message.saveChanges();
        	
        	Transport.send(message);
        	
        	
       
        }catch(Exception e){
        	System.out.println(e.getMessage());
        }
		
	}
	
	public void sendMultiples(String subject, ArrayList<String> emails, String message){
		
		for(String email:emails){
			send(subject ,email, message);
		}
	}
	
	private void createSession(){
		
		try{
			session = Session.getInstance(configProperties,
	        		new javax.mail.Authenticator(){
	        			protected PasswordAuthentication getPasswordAuthentication(){
	        				return new PasswordAuthentication(email,password);
	        			}
	        });
		}
		catch(SecurityException e){
			System.out.println(e.getMessage());
		}
		
	}
	
	private void configureProperties(){
		
		configProperties = new Properties();
		
		configProperties.put("mail.smtp.host", "smtp.gmail.com");
		configProperties.put("mail.smtp.socketFactory.port", "465");
		configProperties.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		configProperties.put("mail.smtp.auth", "true");
		configProperties.put("mail.smtp.port", "465");
		
	}


}
